package com.hwd.gmall.web.controller;

import com.hwd.gmall.oauth.feign.OauthFeignClient;
import com.hwd.gmall.oauth.feign.util.AuthToken;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录的控制层
 *
 * @author 黄伟东/Victor
 * @date 2022/5/8 1:17
 */
@Controller
@RequestMapping(value = "/web/user/login")
public class UserLoginController {

    @Resource
    private OauthFeignClient oauthFeignClient;

    @Resource
    private HttpServletResponse response;

    private static final String TOKEN = "token";

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    @Value("${auth.cookiePath}")
    private String cookiePath;

    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    /**
     * 自定义登录
     *
     * @param username 用户名
     * @param password 密码
     * @return java.lang.String
     */
    @GetMapping
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model model) {
        // 调用认证微服务，登录认证
        AuthToken authToken = oauthFeignClient.login(username, password);

        // 判断是否登录成功
        if (authToken == null || StringUtils.isEmpty(authToken.getAccessToken())) {
            // 账号或者密码错误，重新登录
            model.addAttribute("msg", "账号或者密码错误，请重新登录");
            return "login";
        }
        // 把token放到cookie中
        response.addCookie(getCookie(authToken));

        // 打开首页
        return "forward:index";
    }

    /**
     * 设置cookie
     *
     * @param authToken token
     * @return javax.servlet.http.Cookie
     */
    private Cookie getCookie(AuthToken authToken) {
        Cookie cookie = new Cookie(TOKEN, authToken.getAccessToken());
        cookie.setDomain(cookieDomain);
        cookie.setPath(cookiePath);
        cookie.setMaxAge(cookieMaxAge);
        return cookie;
    }
}
